import 'dart:io';

import 'package:flutter/material.dart';
import 'package:qunaimedical/components/comment_bar.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/doctor_summary_card.dart';
import 'package:qunaimedical/components/item_comment.dart';
import 'package:qunaimedical/components/item_option.dart';
import 'package:qunaimedical/components/item_receiver.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/components/rounded_network_image.dart';
import 'package:qunaimedical/models/comment.dart';
import 'package:qunaimedical/models/consultation_record.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/user.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/comment_page.dart';
import 'package:qunaimedical/pages/consultation.dart';
import 'package:qunaimedical/pages/conversations/custom_video_player.dart';
import 'package:qunaimedical/pages/web_page.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:share/share.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

import '../models/doctor.dart';

/// 预约记录详情
class RecordDetailPage extends StatefulWidget {
  final String id;

  const RecordDetailPage({Key key, @required this.id}) : super(key: key);

  @override
  _RecordDetailPageState createState() => _RecordDetailPageState();
}

class _RecordDetailPageState extends State<RecordDetailPage> {
  ConsultationRecord _item;

  List<String> _images = [];
  List<String> _videos = [];

  TextEditingController _commentController = TextEditingController();

  /// 评论列表
  List<Comment> _comments = [];

  @override
  void initState() {
    super.initState();
    _fetchData();
    _getCommentList();
  }

  @override
  Widget build(BuildContext context) {
    var menus = [
      PopupMenuItem(
        value: 0,
        child: Row(
          children: [
            Image.asset(
              (_item?.whetherAppointed ?? '0') == '0'
                  ? 'assets/images/ic_favorite.png'
                  : 'assets/images/ic_favorited.png',
              width: 20,
              height: 20,
              color: (_item?.whetherAppointed ?? '0') == '0'
                  ? Colors.black87
                  : Colors.yellow,
            ),
            SizedBox(width: 8),
            Text('收藏'),
          ],
        ),
      ),
      PopupMenuItem(
        value: 1,
        child: Row(
          children: [
            Image.asset(
              'assets/images/ic_forward.png',
              width: 18,
              height: 18,
              color: Colors.black87,
            ),
            SizedBox(width: 10),
            Text('分享'),
          ],
        ),
      )
    ];
    return Scaffold(
      appBar: AppBar(
        title: Text('详情'),
        actions: [
          IconButton(
              icon: Icon(Icons.more_horiz),
              onPressed: () {
                showMenu(
                  context: context,
                  position: RelativeRect.fromLTRB(
                      MediaQuery.of(context).size.width, kToolbarHeight, 0, 0),
                  items: menus,
                ).then((value) {
                  // 收藏
                  if (value == 0) {
                    if (_item.whetherAppointed == '0' ||
                        _item.whetherAppointed == '') {
                      _addFavorite();
                    } else {
                      _removeFavorite();
                    }
                  }
                  // 转发
                  if (value == 1) {
                    if (_item != null &&
                        _item.meetingUrl != null &&
                        _item.meetingUrl != '') {
                      if (Platform.isAndroid) {
                        CommonUtils.shareLinkToWinXin(
                            context, _item.meetingUrl);
                      } else {
                        Share.share(_item.meetingUrl);
                      }
                    } else {
                      ToastUtil.show('会诊直播地址为空，无法分享。', context);
                    }
                  }
                });
              })
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: CustomScrollView(
              slivers: [
                _buildContent(),
                _buildReceivers(),
                SliverToBoxAdapter(
                  child: PrimaryLabel('评论'),
                ),
                // 评论列表
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (c, i) => ItemComment(
                      _comments[i],
                      onDelete: () {
                        DialogUtils.showAlertDialog(context, '提示', '确认删除这条评论？',
                            onPressed: () {
                          Navigator.pop(context);
                          _delete(i);
                        });
                      },
                      onReply: () {
                        Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (c) =>
                                        CommentPage(item: _comments[i])))
                            .then((value) {
                          if (value != null && value) {
                            _getCommentList();
                          }
                        });
                      },
                    ),
                    childCount: _comments.length,
                  ),
                ),
              ],
            ),
          ),
          CommentBar(
            hintText: '评论一下',
            controller: _commentController,
            onSendPressed: _comment,
          ),
        ],
      ),
    );
  }

  /// 创建评论
  void _comment() async {
    CommonUtils.hideKeyboard(context);
    String content = _commentController.text.trim();
    if (SPUtils.getUser() == null) {
      DialogUtils.showAlertDialog(context, '提示', '请先进行登录');
      return;
    }
    if (content.isEmpty) {
      ToastUtil.show('评论内容不能为空', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postJson(Urls.COMMENT_ADD, {
      "timelyConsultationId": widget.id, // 所评论预约单ID
      "content": content, // 评论内容
      "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
    });
    Navigator.pop(context);
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        _commentController.clear();
        _getCommentList();
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _getCommentList() async {
    var data = await XHttp.postJson(Urls.COMMENT_LIST, {
      "pageNo": 1, // 起始页（必填）
      "pageSize": 1000, // 分页大小（必填）
      "timelyConsultationId": widget.id, // 预约单ID/咨询单ID（必填）
      "doctorId": "" // 暂传空字符串（必填）
    });
    if (data != null && mounted) {
      ListResponse response = ListResponse.fromJson(data);
      if (response.code == 1) {
        setState(() {
          _comments = List.from(response.data.map((e) => Comment.fromJson(e)));
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  /// 删除评论
  void _delete(int index) async {
    DialogUtils.showWaitDialog(context);
    // 判断是评论还是回复
    var data;
    if (_comments[index].byRepliedId == null) {
      // 删除评论
      data = await XHttp.postJson(Urls.COMMENT_REMOVE, {
        "id": _comments[index].id, // 评论ID
        "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
      });
    } else {
      // 删除回复
      data = await XHttp.postJson(Urls.REPLY_REMOVE, {
        "id": _comments[index].id, // 回复ID
        "commentId": _comments[index].commentId, // 评论ID
        "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
      });
    }
    Navigator.pop(context);
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        setState(() {
          _comments.removeAt(index);
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  SliverList _buildReceivers() {
    List<Doctor> receivers = (_item == null || _item.doctorInfoList.isEmpty)
        ? []
        : _item.doctorInfoList
            .where((element) => element.doctorRole == 'receiveDoctor')
            .toList();
    return SliverList(
        delegate: SliverChildBuilderDelegate(
      (c, i) {
        if (i == 0) {
          return Column(children: [
            CustomDivider(),
            PrimaryLabel('接受人'),
            ItemReceiver(item: receivers[i], clickable: false),
          ]);
        } else {
          return Column(children: [
            Divider(),
            ItemReceiver(item: receivers[i], clickable: false),
          ]);
        }
      },
      childCount: receivers.length,
    ));
  }

  SliverToBoxAdapter _buildContent() {
    var paddingValue = EdgeInsets.only(left: 16, right: 16, bottom: 16);
    Doctor creator;
    if (_item != null && _item.doctorInfoList.isNotEmpty) {
      try {
        creator = _item.doctorInfoList
            .firstWhere((element) => element.doctorRole == 'initiateDoctor');
      } catch (e) {
        print(e);
      }
    }
    return SliverToBoxAdapter(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          CustomDivider(),
          ItemOption(
              text: '会诊直播间',
              imagePath: 'assets/images/ic_live.png',
              onTap: () {
                if (_item != null && _item.meetingUrl.isNotEmpty) {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) =>
                              WebPage(url: _item.meetingUrl)));
                }
              }),
          CustomDivider(),
          DoctorSummaryCard(
            item: creator,
            margin: EdgeInsets.symmetric(horizontal: 10),
          ),
          PrimaryLabel('基本信息'),
          Container(
            height: 50,
            color: Colors.white,
            padding: paddingValue,
            alignment: Alignment.centerLeft,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisSize: MainAxisSize.min,
              children: [
                // Text('失效时间：${_item.}'),
                Text(
                    '就诊时间：${_item?.freeTime ?? ''} ${_item?.morningAfternoon ?? ''}',
                    style: TextStyle(color: Colors.grey[700])),
              ],
            ),
          ),
          CustomDivider(),
          PrimaryLabel('主题'),
          Container(
            color: Colors.white,
            padding: paddingValue,
            child: Text(_item?.title ?? '',
                style: TextStyle(color: Colors.grey[700])),
          ),
          CustomDivider(),
          PrimaryLabel('主诉'),
          Container(
            color: Colors.white,
            padding: paddingValue,
            child: Text(_item?.content ?? '',
                style: TextStyle(color: Colors.grey[700])),
          ),
          CustomDivider(),
          Offstage(
            child: PrimaryLabel('图片'),
            offstage: _images.isEmpty,
          ),
          Offstage(
            offstage: _images.isEmpty,
            child: Container(
              color: Colors.white,
              height: 90,
              width: double.maxFinite,
              alignment: Alignment.topLeft,
              padding: paddingValue,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                itemBuilder: (c, i) {
                  return InkWell(
                    onTap: () => CommonUtils.openGallery(context,
                        _images.map((e) => Urls.BASE_URL + e).toList(), i),
                    child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(6)),
                      child:
                          RoundedNetWorkImage('${Urls.BASE_URL}${_images[i]}'),
                    ),
                  );
                },
                itemCount: _images.length,
                separatorBuilder: (BuildContext context, int index) {
                  return SizedBox(width: 10);
                },
              ),
            ),
          ),
          CustomDivider(),
          Offstage(
            child: PrimaryLabel('视频'),
            offstage: _videos.isEmpty,
          ),
          Offstage(
            offstage: _videos.isEmpty,
            child: Container(
              color: Colors.white,
              height: 90,
              width: double.maxFinite,
              alignment: Alignment.topLeft,
              padding: paddingValue,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                itemBuilder: (c, i) {
                  return InkWell(
                    onTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (c) => CustomVideoPlayer(
                                  '${Urls.BASE_URL}${_videos[i]}')));
                    },
                    child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(6)),
                      child: GenThumbnailImage(
                          thumbnailRequest: ThumbnailRequest(
                              video: '${Urls.BASE_URL}${_videos[i]}',
                              thumbnailPath: null,
                              imageFormat: ImageFormat.JPEG,
                              maxHeight: 200,
                              maxWidth: 200,
                              timeMs: 0,
                              quality: 50)),
                    ),
                  );
                },
                itemCount: _videos.length,
                separatorBuilder: (BuildContext context, int index) {
                  return SizedBox(width: 10);
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _fetchData() async {
    var data = await XHttp.postJson(Urls.RECORD_DETAIL, {
      'id': widget.id,
      "orderState": "1",
      'doctorId': SPUtils.getUser()?.id ?? '',
    });
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 1) {
        ConsultationRecord item = ConsultationRecord.fromJson(response.data);
        setState(() {
          _item = item;
          _images = (_item == null || _item.appointmentImag.isEmpty)
              ? []
              : _item.appointmentImag.split(',');
          _videos = (_item == null || _item.video.isEmpty)
              ? []
              : _item.video.split(',');
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _addFavorite() async {
    User user = SPUtils.getUser();
    if (user != null) {
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(Urls.FAVORITE_ADD, {
        'accountId': user.id,
        'recordId': widget.id,
        'recordType': 'appointment_record',
      });
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          setState(() {
            _item.whetherAppointed = '1';
          });
          ToastUtil.show('收藏成功', context);
        }
      }
    }
  }

  void _removeFavorite() async {
    User user = SPUtils.getUser();
    if (user != null) {
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(Urls.FAVORITE_REMOVE, {
        'accountId': user.id,
        'recordId': widget.id,
        'recordType': 'appointment_record',
      });
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          if (mounted) {
            setState(() {
              _item.whetherAppointed = '0';
              ToastUtil.show('已取消收藏', context);
            });
          }
        }
      }
    } else {}
  }
}
